package com.sqstudio.exercise.chapter4{
	
	import flash.events.Event;
	
	import gs.TweenLite;
	
	import org.papervision3d.core.proto.MaterialObject3D;
	import org.papervision3d.events.InteractiveScene3DEvent;
	import org.papervision3d.materials.ColorMaterial;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.primitives.Cylinder;
	import org.papervision3d.objects.primitives.Plane;
	import org.papervision3d.view.BasicView;

	[SWF(width="800",height="600")]
	/**
	 *走马灯效果 
	 * @author Nestor
	 * 
	 * 单片角度的三种算法和效果
	 * 1.官方：- Math.atan2(plane.x,plane.z) * 180 / Math.PI;
	 * 2.插页： Math.atan(plane.z/plane.x) * 180 / Math.PI;
	 * 3.圆筒：Math.atan(plane.z/plane.x) * 180 / Math.PI +90;
	 */	
	public class CarouselExample extends BasicView
	{
		private var do3d:DisplayObject3D;
		public function CarouselExample(viewportWidth:Number=800, viewportHeight:Number=600, scaleToStage:Boolean=true, interactive:Boolean=false, cameraType:String="Target")
		{
			super(viewportWidth, viewportHeight, scaleToStage, interactive, cameraType);
			stage.frameRate = 40;
			init();
			this.startRendering();
		}
		
		private function init():void{
			this.do3d = new DisplayObject3D();
			scene.addChild(this.do3d);
			
			var cylinder:Cylinder = new Cylinder(null,250,180,15,2);
			
			var len:int = cylinder.geometry.vertices.length;
			for (var i:int = 0; i < len; i++) 
			{
				var plane:Plane = new Plane(getMaterial(),75,75,2,2);
				plane.x = cylinder.geometry.vertices[i].x;
				plane.y = cylinder.geometry.vertices[i].y;
				plane.z = cylinder.geometry.vertices[i].z;
				plane.addEventListener(InteractiveScene3DEvent.OBJECT_CLICK,planeCKhandler);
				plane.localRotationY =  Math.atan(plane.z/plane.x) * 180 / Math.PI +90;
//				plane.localRotationY = - Math.atan2(plane.x,plane.z) * 180 / Math.PI;
				do3d.addChild(plane);
			}
			
			camera.z = 100;
			camera.zoom = 40;
			viewport.interactive = true;
		}
		
		private function planeCKhandler(e:InteractiveScene3DEvent):void
		{
			TweenLite.to(e.displayObject3D,1,{localRotationY:"180"});
		}
		
		private function getMaterial():MaterialObject3D{
			var colorMaterial:ColorMaterial = new ColorMaterial(0xffffff * Math.random());
			colorMaterial.doubleSided = true;
			colorMaterial.interactive = true;
			return colorMaterial;
		}
		
		override protected function onRenderTick(event:Event=null):void
		{
			do3d.localRotationY+= (stage.mouseX - stage.stageWidth/2)/300
			super.onRenderTick(event);
		}
	}
}